<template>
  <view style="width: 100%;height: 100%;">
    <view class="root">
      <view class="content">
        <uni-forms ref="formRef" :model="form" validateTrigger="blur" label-position="top" label-width="100%"
          err-show-type="toast">
          <view class="content-wrapper">
            <yy-title title="当户信息"></yy-title>
            <view class="content-inner-wrapper">
              <uni-forms-item label="当户姓名:" name="pawnName" required key="pawnName">
                <view class="form-content-item" :class="form.pawnName ?  '' : 'input-item'">
                  <uni-easyinput type="text" v-model="form.pawnName" :inputBorder="false" placeholder="请填写"
                    :clearable="true" />
                </view>
              </uni-forms-item>
              <uni-forms-item label="联系方式:" name="pawnPhone" required key="pawnPhone">
                <view class="form-content-item" :class="form.pawnPhone ?  '' : 'input-item'">
                  <uni-easyinput type="text" v-model="form.pawnPhone" :inputBorder="false" placeholder="请填写"
                    :clearable="true" />
                </view>
              </uni-forms-item>
              <uni-forms-item label="身份证号:" name="pawnIdCard" required key="pawnIdCard">
                <view class="form-content-item" :class="form.pawnIdCard ?  '' : 'input-item'">
                  <uni-easyinput type="idcard" :maxlength="18" v-model="form.pawnIdCard" :inputBorder="false"
                    placeholder="请填写" :clearable="true" />
                </view>
              </uni-forms-item>
            </view>
          </view>
          <view class="content-wrapper">
            <yy-title title="当物信息"></yy-title>
            <view class="pawn-list-wrapper" v-for="(item, index) in form.pawnItemList" :key="item.uid">
              <view class="title-name">
                <view class="name-i">
                  {{item.pawnItemName}}
                </view>
                <view class="delete-i" @click="handleDeletePawn(index)">
                  <u-icon name="minus-circle" color="#F94A4A" size="22rpx"></u-icon>
                  <view class="text-delete">
                    删除
                  </view>
                </view>
              </view>
              <view class="i-item">
                <view class="i-label">
                  规格状况
                </view>
                <view class="i-value">
                  {{item.pawnItemSpecifications}}
                </view>
              </view>
              <view class="i-item">
                <view class="i-label">数量</view>
                <view class="i-value">
                  {{item.pawnItemNumber}}
                </view>
              </view>
              <view class="i-item">
                <view class="i-label">
                  金额
                </view>
                <view class="i-value">
                  {{item.pawnItemMoney}}元
                </view>
              </view>
            </view>
            <yy-button-list text="添加典当物品" @click="handleAddPawn"></yy-button-list>
          </view>
          <view class="content-wrapper">
            <yy-title title="典当信息"></yy-title>
            <uni-forms-item label="典当期限:" name="fZdgzFwlx" required key="fZdgzFwlx">
              <view class="datetime-picker-wrapper">
                <view class="start-t t-item" :class="form.pawnStartTime ? 'has-value' : ''" @click="handleStartTime">
                  {{form.pawnStartTime ? form.pawnStartTime : '请选择开始日期'}}
                </view>
                <view class="text-t">
                  至
                </view>
                <view class="end-t t-item" :class="form.pawnEndTime ? 'has-value' : ''" @click="handleEndTime">
                  {{form.pawnEndTime ? form.pawnEndTime : '请选择结束日期'}}
                </view>
              </view>
            </uni-forms-item>
          </view>
        </uni-forms>
      </view>
      <view class="bottom">
        <yy-button-submit @submit="onSubmit"></yy-button-submit>
      </view>
    </view>
    <!-- 添加典当物 -->
    <u-popup :show="visiblePawn" mode="bottom" @close="close" @open="open">
      <view class="tenant-info-wrapper">
        <view class="top-title">
          <view class="p-title">添加典当物</view>
          <view class="p-cancel" @click="handleCancelPawn">取消</view>
        </view>
        <view class="popup-form-wrapper">
          <uni-forms ref="pawnFormRef" label-position="top" :rules="pawnFormRules" :model="pawnForm"
            validateTrigger="blur" :border="false" err-show-type="toast" label-width="100%">
            <uni-forms-item label="当物名称:" name="pawnItemName" required key="pawnItemName">
              <view class="form-content-item">
                <uni-easyinput type="text" v-model="pawnForm.pawnItemName" disableColor="#ffffff" :inputBorder="false"
                  placeholder="请填写" :clearable="true" maxlength="30" />
              </view>
            </uni-forms-item>
            <uni-forms-item label="规格和状况:" name="pawnItemSpecifications" required key="pawnItemSpecifications">
              <view class="form-content-item" :class="pawnForm.pawnItemSpecifications ?  '' : 'input-item'">
                <uni-easyinput type="text" v-model="pawnForm.pawnItemSpecifications" disableColor="#ffffff"
                  :inputBorder="false" placeholder="请填写" :clearable="true" maxlength="100" />
              </view>
            </uni-forms-item>
            <uni-forms-item label="数量:" name="pawnItemNumber" required key="pawnItemNumber">
              <view class="form-content-item" :class="pawnForm.pawnItemNumber ?  '' : 'input-item'">
                <uni-easyinput type="number" v-model="pawnForm.pawnItemNumber" disableColor="#ffffff"
                  :inputBorder="false" placeholder="请填写" :clearable="true" />
              </view>
            </uni-forms-item>
            <uni-forms-item label="金额:" name="pawnItemMoney" required key="pawnItemMoney">
              <view class="form-content-item" :class="pawnForm.pawnItemMoney ?  '' : 'input-item'">
                <uni-easyinput type="digit" v-model="pawnForm.pawnItemMoney" disableColor="#ffffff" :inputBorder="false"
                  placeholder="请填写" :clearable="true">
                  <view slot="right" style="font-weight: bold;font-size: 28rpx;color: #000000;padding-right: 20rpx;">元
                  </view>
                </uni-easyinput>
              </view>
            </uni-forms-item>
            <view key="pawnItemPhoto">
              <uni-forms-item label="当物图片: (可上传1张当物照片)" name="pawnItemPhoto" required>
                <u-upload :fileList="pawnForm.pawnItemPhoto" @afterRead="(info) => afterReadFive(info, 'pawnForm', 19)"
                  @delete="(info) => deletePhoto(info, 'pawnForm')" name="pawnItemPhoto" :maxCount="1" :multiple="true"
                  width="96" height="80">
                  <image :src="baseImgUrl + 'upload-icon3.png'" style="width: 200rpx; height: 160rpx"></image>
                </u-upload>
              </uni-forms-item>
            </view>
          </uni-forms>
        </view>
        <yy-button-add text="提交" @click="handleSubmitPawn"></yy-button-add>
      </view>
    </u-popup>
    <div style="position: absolute;width: 0;height: 0;overflow: hidden;">
      <uni-datetime-picker ref="pawnStartTimeRef" type="date" :clear-icon="false" v-model="form.pawnStartTime"
        :end="moment().valueOf()" @change="handleStartTimeChange">
      </uni-datetime-picker>
      <uni-datetime-picker ref="pawnEndTimeRef" type="date" :clear-icon="false" v-model="form.pawnEndTime"
        :start="moment(form.pawnStartTime).add(1, 'days').valueOf()">
      </uni-datetime-picker>
    </div>
  </view>
</template>

<script>
  import _ from '@/utils/lodash.js'
  import uploadFileMixin from '../../utils/upload-file-mixin'
  import {
    Toast,
    generateUrlOptions,
    getOptionsParams,
    idCardRule,
    isLoading,
    navBack,
    phoneRule
  } from '../../utils/util'
  import {
    addPawnRecordDetails
  } from '../../api/api'

  import moment from '../../utils/moment'
  export default {
    mixins: [uploadFileMixin],
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        routerParams: {},
        formRef: null,
        form: this.initForm(),
        rules: {
          pawnName: {
            rules: [{
              required: true,
              errorMessage: "请填写当户姓名！",
            }]
          },
          pawnPhone: {
            rules: phoneRule()
          },
          pawnIdCard: {
            rules: idCardRule()
          },
          pawnItemList: {
            rules: [{
              required: true,
              errorMessage: "请添加典当物信息！",
            }]
          },
          pawnStartTime: {
            rules: [{
              required: true,
              errorMessage: "请选择开始日期！",
            }]
          },
          pawnEndTime: {
            rules: [{
              required: true,
              errorMessage: "请选择结束日期！",
            }]
          },
        },
        // 添加典当物
        visiblePawn: false,
        pawnForm: this.initPawnForm(),
        pawnFormRef: null,

        pawnFormRules: {
          pawnItemName: {
            rules: [{
              required: true,
              errorMessage: "请填写当物名称！",
            }]
          },
          pawnItemSpecifications: {
            rules: [{
              required: true,
              errorMessage: "请填写规格和状况！",
            }]
          },
          pawnItemNumber: {
            rules: [{
              required: true,
              errorMessage: "请填写数量！",
            }]
          },
          // if (businessArea && !isNumberTwo(businessArea)) {
          //   Toast("营业面积请输入数字,可精确到小数点后两位");
          //   return;
          // }
          pawnItemMoney: {
            rules: [{
                required: true,
                errorMessage: "请填写金额！",
              },
              {
                pattern: '^(\\d+\\.?)?\\d{0,2}$',
                errorMessage: '金额请输入数字,可精确到小数点后两位！'
              }
            ]
          },
          pawnItemPhoto: {
            rules: [{
              required: true,
              errorMessage: "请上传当物图片！",
            }]
          },
        },
        pawnStartTimeRef: null,
        pawnEndTimeRef: null
      }
    },
    onLoad(options) {
      this.routerParams = getOptionsParams(options)
      console.log(this.routerParams)
    },
    onReady() {
      this.$refs.formRef.setRules(this.rules)
      this.$refs.pawnFormRef.setRules(this.pawnFormRules)
    },
    methods: {
      moment,
      initForm() {
        return {
          pawnName: '',
          pawnPhone: '',
          pawnIdCard: '',
          pawnStartTime: '',
          pawnEndTime: '',
          // 当物信息
          pawnItemList: []
        }
      },
      initPawnForm() {
        return {
          pawnItemName: '',
          pawnItemSpecifications: '',
          pawnItemNumber: '',
          pawnItemMoney: '',
          pawnItemPhoto: [],
        }
      },
      onSubmit() {
        this.$refs.formRef.validate().then(() => {
            // 判断是否 有典当物信息
            if (this.form.pawnItemList && !this.form.pawnItemList[0]) {
              Toast('请上传当物信息！')
              return
            }
            if (!this.form.pawnStartTime) {
              Toast('请选择开始日期!')
              return
            }
            if (!this.form.pawnEndTime) {
              Toast('请选择结束日期!')
              return
            }
            let data = {
              companyMessageId: this.routerParams.companyMessageId,
              ...this.form,
              pawnStartTime: moment(this.form.pawnStartTime).format('YYYY/MM/DD HH:mm:ss'),
              pawnEndTime: moment(this.form.pawnEndTime).format('YYYY/MM/DD HH:mm:ss'),
            };


            // 处理图片信息
            if (data.pawnItemList) {
              data.pawnItemList = data.pawnItemList.map(item => {
                return {
                  ...item,
                  pawnItemPhoto: item.pawnItemPhoto.map(item => item.halfPath).join()
                }
              })
            }
            isLoading(true)
            addPawnRecordDetails(data).then((res) => {
                if (res.code == 200) {
                  Toast(res.message);
                  uni.$emit('add-pawn-success')
                  setTimeout(() => {
                    navBack();
                  }, 100)
                }
              })
              .finally(() => {
                isLoading(false)
              })
          })
          .catch(() => {})

      },
      handleAddPawn() {
        this.visiblePawn = true
      },
      handleCancelPawn() {
        this.visiblePawn = false
      },
      handleSubmitPawn() {
        this.$refs.pawnFormRef.validate().then(res => {
          this.form.pawnItemList.push({
            ...this.pawnForm,
            uid: _.uniqueId()
          })
          this.pawnForm = this.initPawnForm()
          this.visiblePawn = false
        }).catch(err => {})
      },
      open() {

      },
      close() {

      },
      handleDeletePawn(index) {
        uni.showModal({
          title: "提示",
          content: "请确认是否删除？",
          confirmColor: "#2488F5",
          success: async (res) => {
            if (res.confirm) {
              // 删除
              this.form.pawnItemList.splice(index, 1)
            } else if (res.cancel) {}

          },
        });
      },
      handleTime(val) {
        if (val) {
          this.form.pawnStartTime = val[0]
          this.form.pawnEndTime = val[1]
        }
      },
      handleStartTime() {
        this.$refs.pawnStartTimeRef.show()
      },
      handleEndTime() {
        // 看有没有选开始时间
        if (!this.form.pawnStartTime) {
          Toast('请选择开始日期！')
          return
        }
        this.$refs.pawnEndTimeRef.show()
      },
      handleStartTimeChange() {
        this.form.pawnEndTime = ''
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../../styles/uni-form-label-top.scss';

  .root {
    display: flex;
    width: 100%;
    height: 100%;
    flex-direction: column;
    background: #F9F9F9;

    .content {
      flex: 1;
      height: 0;
      overflow: auto;

      .content-wrapper {
        background: #FFFFFF;
        box-shadow: 0rpx 3rpx 6rpx 1rpx rgba(207, 207, 207, 0.1608);
        border-radius: 8rpx 8rpx 8rpx 8rpx;
        padding: 40rpx 20rpx;
        margin-bottom: 10rpx;
      }

      .pawn-list-wrapper {
        background: #F9F9F9;
        padding: 25rpx;
        margin-bottom: 10rpx;

        .title-name {
          display: flex;
          justify-content: space-between;
          margin-bottom: 23rpx;

          .name-i {
            font-weight: bold;
            font-size: 32rpx;
            color: #181818;
          }

          .delete-i {
            display: flex;
            align-items: center;
            font-weight: 500;
            font-size: 26rpx;
            color: #F94A4A;
            flex-shrink: 0;

            .text-delete {
              margin-left: 10rpx;
            }
          }
        }

        .i-item {
          margin-bottom: 15rpx;
          display: flex;

          .i-label {
            font-weight: 500;
            font-size: 28rpx;
            color: #999999;
            width: 119rpx;
            margin-right: 16rpx;
            position: relative;
            text-align: justify;
            text-align-last: justify;
            flex-shrink: 0;



            &::after {
              content: ':';
              position: absolute;
              right: -8rpx;
            }
          }

          .i-value {
            font-weight: bold;
            font-size: 28rpx;
            color: #101010;
          }

        }
      }

      .datetime-picker-wrapper {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .text-t {
          font-weight: 500;
          font-size: 30rpx;
          color: #666666;
        }

        .t-item {
          font-weight: 400;
          font-size: 28rpx;
          color: #A2A2A2;
          width: 304rpx;
          height: 70rpx;
          background: #F9F9F9;
          border-radius: 8rpx 8rpx 8rpx 8rpx;
          border: 1rpx solid #F1EEEE;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .has-value {
          font-weight: bold;
          font-size: 30rpx;
          color: #181818;
        }
      }
    }
  }


  .tenant-info-wrapper {
    height: 80vh;
    display: flex;
    flex-direction: column;
    padding-top: 30rpx;

    .top-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 134rpx;
      padding: 0 18rpx;


      .p-title {
        font-weight: bold;
        font-size: 30rpx;
        color: #101010;
      }

      .p-cancel {
        font-weight: 500;
        font-size: 28rpx;
        color: #666666;
      }
    }

    .popup-form-wrapper {
      flex: 1;
      overflow: auto;
      height: 0;
    }

    .submit-tenant-info {
      margin-bottom: 17rpx;
      width: 680rpx;
      height: 88rpx;
      background: #2488F5;
      border-radius: 44rpx 44rpx 44rpx 44rpx;
      border: 1rpx solid #ACCBEC;
      font-weight: 500;
      font-size: 36rpx;
      color: #F9F9F9;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 85rpx;
    }
  }
</style>